package com.vancouver.knows.ui.activity.citydiscount;

import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.DeviceUtil;
import com.pangu.util.StringUtil;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.ui.activity.CommentDetailActivity;
import com.vancouver.knows.ui.activity.userpost.CreateUserPostActivity;
import com.vancouver.knows.ui.fragment.citydiscount.CityDiscountPostMainDetailView;
import com.vancouver.knows.ui.fragment.citydiscount.WeChatView;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.CityDiscountDetailInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchDiscountDetailTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteUpvoteTaskMark;
import com.vancouver.knows.business.task.mark.UserFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserUpvoteTaskMark;

/**
 * 城惠详情
 * 
 * @author cxlin
 * 
 */
public class CityDiscountDetailActivity extends CommentDetailActivity<CityDiscountDetailInfo> {

	private CityDiscountPostMainDetailView mainDetailView;
	private WeChatView weChatView;

	@Override
	protected void customizeLoadingView() {
		LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
		ImageView loadingImageView = new ImageView(this);
		loadingImageView.setLayoutParams(linearLayoutParams);
		loadingImageView.setImageResource(R.drawable.loading_business_detail);
		loadingImageView.setScaleType(ImageView.ScaleType.FIT_XY);
		((RelativeLayout) loadingView).addView(loadingImageView, 0);
	}

	@Override
	protected void updateInfo() {
		info = bModule.getCacheManager().getDiscountDetailInfoMap().get(postId);

		if (info != null) {
			if (!StringUtil.isEmptyString(info.getWeChatId()) && !StringUtil.isEmptyString(info.getWeChatQr())) {
				weChatView = new WeChatView(this, info.getWeChatId(), info.getWeChatQr());
				weChatContainer.addView(weChatView.getWeChatView());
			}
		}
	}

	@Override
	protected void loadInfo(int type) {
		String userId = bModule.getCacheManager().getUserInfo() == null ? "" : bModule.getCacheManager().getUserInfo()
				.getUserID();
		ATaskMark aTaskMark = bModule.getTaskMarkPool().getFetchDiscountDetailTaskMark(postId);
		aTaskMark.setTaskType(type);
		bModule.getServiceWrapper().fetchDiscountDetail(this, aTaskMark, postId, userId, imContext.latitude, imContext.longitude);
	}

	@Override
	protected void subInit() {
		toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				switch (item.getItemId()) {
				case R.id.menu_item_upvote: {
					upvote();
					Tracker t = ((MainApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
					t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYDISCOUNT_DETAIL);
					t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
							.setAction(AnalyticsConstants.ACTION_ONCLICK)
							.setLabel(AnalyticsConstants.LABEL_CITYDISCOUNT_DETAIL_MENU_UPVOTE).build());
				}
					break;
				case R.id.menu_item_follow: {
					Tracker t = ((MainApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
					t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYDISCOUNT_DETAIL);
					t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
							.setAction(AnalyticsConstants.ACTION_ONCLICK)
							.setLabel(AnalyticsConstants.LABEL_CITYDISCOUNT_DETAIL_MENU_FOLLOW).build());

					if (!AppUtils.getLoginStatus(CityDiscountDetailActivity.this)) {
						return true;
					}

					UserInfo userInfo = bModule.getCacheManager().getUserInfo();

					if ("Y".equals(info.getUserFollowed())) {
						UserDeleteFollowTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteFollowTaskMark(
								info.getId());
						bModule.getServiceWrapper().userDeleteFollow(CityDiscountDetailActivity.this, taskMark,
								info.getId(), userInfo.getUserID());

					} else {
						UserFollowTaskMark taskMark = bModule.getTaskMarkPool().getUserFollowTaskMark(info.getId());
						bModule.getServiceWrapper().userFollow(CityDiscountDetailActivity.this, taskMark, info.getId(),
								userInfo.getUserID());
					}
				}
					break;
				case R.id.menu_item_share:
					Tracker t = ((MainApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
					t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYDISCOUNT_DETAIL);
					t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
							.setAction(AnalyticsConstants.ACTION_ONCLICK)
							.setLabel(AnalyticsConstants.LABEL_CITYDISCOUNT_DETAIL_MENU_SHARE).build());

					AppUtils.shareContent(CityDiscountDetailActivity.this, info.getName(), info.getPermalink(),
							info.getThumbnail());
					break;
				default:
					break;
				}
				return true;
			}
		});

		mainDetailView = new CityDiscountPostMainDetailView(this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
		detailContentLayout.addView(mainDetailView.getRootView(), 0, lp);
		invalidateOptionsMenu();
	}

	@Override
	protected int commentCount() {
		return info.getCommentCount();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_citydiscount_detail, menu);
		MenuItem delMenuItem = menu.findItem(R.id.menu_item_delete);
		if (delMenuItem != null) {
			delMenuItem.setVisible(false);
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		if (info == null) {
			return true;
		}

		MenuItem upvoteMenuItem = menu.findItem(R.id.menu_item_upvote);
		int upvoteIconResId = "Y".equals(info.getUserUpvoted()) ? R.drawable.menu_icon_liked
				: R.drawable.menu_icon_like;
		upvoteMenuItem.setIcon(getResources().getDrawable(upvoteIconResId));

		MenuItem followMenuItem = menu.findItem(R.id.menu_item_follow);
		int followIconResId = "Y".equals(info.getUserFollowed()) ? R.drawable.menu_icon_followed
				: R.drawable.menu_icon_follow;
		followMenuItem.setIcon(getResources().getDrawable(followIconResId));

		return true;
	}

	public void upvote() {
//		if (!AppUtils.getLoginStatus(this)) {
//			return;
//		}
//
//		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		String userId = null;
		String auid = null;
		if (userInfo != null) {
			userId = userInfo.getUserID();
		} else {
			BSharedPrefManager sharedPrefManager = imContext.getSharedPrefManager();
			auid = sharedPrefManager.getAuid();
		}

		if ("Y".equals(info.getUserUpvoted())) {
			UserDeleteUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteUpvoteTaskMark(info.getId(), "post", info.getId());
			bModule.getServiceWrapper().userDeleteUpvote(CityDiscountDetailActivity.this, taskMark, userId,auid,  info.getId(), "post");

		} else {
			UserUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserUpvoteTaskMark(info.getId(), "post", info.getId());
			bModule.getServiceWrapper().userUpvote(CityDiscountDetailActivity.this, taskMark, userId,auid, info.getId(), "post");
		}
	}

	@Override
	public void subHandleMessage(Message msg) {
		super.subHandleMessage(msg);

		switch (msg.what) {
			case Constants.BUSINESS_STATUS_CITYDISCOUNT_IMAGES_CHANGE:
				mainDetailView.setUserImages(bModule.getCacheManager().getDiscountDetailInfoMap().get(info.getId()).getBusinessUserImages());
				break;
			case Constants.BUSINESS_STATUS_USER_COMMENT_UPVOTE:
			case Constants.BUSINESS_STATUS_USER_DELETE_COMMENT_UPVOTE:
				mainDetailView.subHandleMessage(msg);

				break;
			case Constants.BUSINESS_STATUS_DEL_USER_COMMENT:
				loadInfo(ATaskMark.TYPE_REFRESH);
				break;
		}
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		super.receiveResult(taskMark, exception, trackerResult);

		if (taskMark instanceof FetchDiscountDetailTaskMark) {
			updateInfo();
			if (taskMark.getTaskType() == ATaskMark.TYPE_REFRESH) {
				mainDetailView.taskMarkRefreshOver(taskMark);
				if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
					updateCommentBtn();
				}

			} else {
				if (taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR) {
					Toast.makeText(this, R.string.load_error, Toast.LENGTH_SHORT).show();
					finish();
					return;

				} else if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
					init();
				}
			}

		} else if ((taskMark instanceof UserUpvoteTaskMark || taskMark instanceof UserDeleteUpvoteTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			invalidateOptionsMenu();

		} else if ((taskMark instanceof UserFollowTaskMark || taskMark instanceof UserDeleteFollowTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			invalidateOptionsMenu();
			mainDetailView.updatePromotionsView();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CreateUserPostActivity.ADD_PHOTOS_REQUEST && resultCode == RESULT_OK) {
			loadInfo(ATaskMark.TYPE_REFRESH);
		}
	}

	@Override
	protected boolean hasActionButtons() {

		if (info != null) {
			TextView phoneButton = (TextView) actionButtonContainer.findViewById(R.id.phone);
			final TextView weChatButton = (TextView) actionButtonContainer.findViewById(R.id.wechat);

			if (StringUtil.isEmptyString(info.getPhone())) {
				Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_phone);
				drawable.setColorFilter(ContextCompat.getColor(this, R.color.disabled_gray), PorterDuff.Mode.SRC_ATOP);
				phoneButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
				phoneButton.setClickable(false);
			} else {
				Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_phone);
				drawable.clearColorFilter();
				phoneButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
				phoneButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent phoneIntent = new Intent(Intent.ACTION_DIAL);
						phoneIntent.setData(Uri.parse("tel:" + info.getPhone()));
						startActivity(phoneIntent);
					}
				});
			}


			if (StringUtil.isEmptyString(info.getWeChatId())) {
				Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_wechat_filled);
				weChatButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
				weChatButton.setClickable(false);
			} else {
				final Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_wechat);
				final Drawable drawableSelected = ContextCompat.getDrawable(this, R.drawable.action_wechat_collapse);
				weChatButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
				weChatButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (weChatView != null) {
							if (weChatView.getWeChatView().getVisibility() == View.GONE) {
								weChatView.setVisibility(View.VISIBLE);
								weChatButton.setCompoundDrawablesWithIntrinsicBounds(drawableSelected, null, null, null);
							} else {
								weChatView.setVisibility(View.GONE);
								weChatButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
							}
						}
					}
				});
			}

		}

		return true;
	}
}
